/** This Class puts the focus on its given item
 * @author zulianp@lu.unisi.ch & lemmar@lu.unisi.ch
 */
package ch.unisi.inf.projects.java.uom.gui.commands;

import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import javax.swing.Icon;
import java.awt.image.BufferedImage;
import ch.unisi.inf.projects.java.uom.elements.Item;
import ch.unisi.inf.projects.java.uom.elements.ItemManager;
import ch.unisi.inf.projects.java.uom.elements.Photo;

public final class LinkReferenceCommand extends Command{

	private static final long serialVersionUID = -1L;
	private static final int width = 90;
	private static final int height = 70;
	private Item item;
	private String name;
	
	private BufferedImage scaleImage (final BufferedImage image)
	{
		BufferedImage newImage;
		final int iwidth = image.getWidth();
		final int iheight = image.getHeight();
		final double scale = Math.max((1.0 * iwidth) / width, (1.0 * iheight) / height);
		
		newImage = new BufferedImage((int) Math.floor(iwidth / scale), (int) Math.floor(iheight / scale), BufferedImage.TYPE_INT_RGB);
        for(int y = 0; y < iheight/scale; y++) {
        	for(int x = 0; x < iwidth/scale; x++) {
        		if (Math.floor(x * scale) > iwidth || Math.floor(y * scale) > iheight)
        			continue;
        		try {
        			newImage.setRGB(x, y, image.getRGB((int) Math.floor(x * scale), (int) Math.floor(y * scale)));
                }
               	catch (final ArrayIndexOutOfBoundsException e)
               	{
               		continue;
               	}
            }
        }
        return newImage;
	}
	
	public LinkReferenceCommand(final Item item)
	{
		if(item != null) {
			this.item = item;
			name = item.getField("STRING_NAME");
			if(name == null)
				name = item.getName();
			putValue(NAME, name);
			putValue(SHORT_DESCRIPTION, "click here to open " + name);
		  
			try {
				Photo preview = (Photo)item.getPreview();
				if(preview != null)
				{
					final BufferedImage image = preview.view();
					final Icon icon = new ImageIcon(scaleImage(image));
					putValue(SMALL_ICON, icon);
				}
			}
			catch (final Exception ex) {
				return;
			}
		}
		
	}
	public void actionPerformed(final ActionEvent ev) {
		
		if(item != null) {
		ItemManager manager= ItemManager.instance();
		manager.fireFocusOnItem(item);
		}
	}

}
